package com.dudu.controller;

import static com.dudu.util.SendSmsUtil.SEND_LIMIT;

import com.alibaba.fastjson.JSONObject;
import com.dudu.cache.Cache;
import com.dudu.exception.ErrorCode;
import com.dudu.model.vo.AppRequest;
import com.dudu.model.vo.SmsCodeVO;
import com.dudu.util.Const;
import com.dudu.util.ControllerUtils;
import com.dudu.util.DateUtil;
import com.dudu.util.ResponseBuilder;
import com.dudu.util.SendSmsUtil;
import com.dudu.util.WebResponse;
import com.dudu.util.WebResponseHelper;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by dudu on 2016/12/24.
 */
@Slf4j
@Controller
@RequestMapping("/v1/common")
public class CommonController {

    public static String MOBILE_PASSCODE = "_mobile_passcode_";

    public static String SEND_SEPERATE = "_send_seperate_";

    private static int TOKEN_TIMEOUT = 60*24*3600;

    @Resource
    private Cache cache;

    @RequestMapping("/smsCode.json")
    @ResponseBody
    public WebResponse<?> sendSmsCode(@RequestBody AppRequest<SmsCodeVO> params) {
        String mobile = params.getData().getMobile();
        String code = SendSmsUtil.createMobileCode();
        log.info("sendSmsCode mobile:{}, code:{}", mobile, code);
        if(cache.exists(SEND_SEPERATE + mobile)) {// 一分钟之内不允许重复发送
            return ResponseBuilder.create(ErrorCode.SEND_SMS_ERROR, "获取验证码过于频繁，请1分钟后再试！").build();
        }
//        HashMap<String, Object> result = SendSmsUtil.sendSms(mobile,"23843",code, SEND_LIMIT);
//        if("000000".equals(result.get("statusCode"))){// 发送成功
//            //正常返回输出data包体信息（map）
//            cache.add(MOBILE_PASSCODE + mobile, code, SendSmsUtil.PASSCODE_EXPIRY_IN_SECONDS);
//            cache.add(SEND_SEPERATE + mobile, code, SendSmsUtil.SEND_SEPERATE_IN_SECONDS);
//            log.info("sendSmsCode mobile:{}, code:{}", mobile, code);
//            return ResponseBuilder.create().build();
//        }else{
//            //异常返回输出错误码和错误信息
//            String errMsg = String.valueOf(result.get("statusMsg"));
//            log.error("sendSmsCode occurs error: {}", errMsg);
//            return ResponseBuilder.create(ErrorCode.SEND_SMS_ERROR, errMsg).build();
//        }

        return ResponseBuilder.create().build();
    }

    @RequestMapping("/token.json")
    @ResponseBody
    public WebResponse<?> token(@RequestBody AppRequest<String> params) {
        String uuid = params.getUuid();
        String appSecret = params.getData();
        Long ts = params.getTs();
        if(!Const.SECRET.equalsIgnoreCase(appSecret)) {
            log.error("v1.common.token: secret is invalid!");
            return ResponseBuilder.create(ErrorCode.PERMISSION_DENIED_ERROR).build();
        }
        if(ts > System.currentTimeMillis() || System.currentTimeMillis()
            - ts > 10 * 60 * 1000) {
            log.error("v1.common.token: ts is invalid!");
            return ResponseBuilder.create(ErrorCode.PERMISSION_DENIED_ERROR).build();
        }
        Map<String, Object> result = new HashedMap();
        if(cache.exists(Const.TOKEN_PREFIX + uuid)) {
            result.put("token", String.valueOf(cache.getValue(Const.TOKEN_PREFIX + uuid)));
            return ResponseBuilder.create().setData(result).build();
        }
        String token = DigestUtils.sha1Hex(DigestUtils.sha1Hex(uuid) + System.currentTimeMillis());
        cache.add(Const.TOKEN_PREFIX + uuid, token, TOKEN_TIMEOUT);
        result.put("token", token);
        result.put("expires_in", TOKEN_TIMEOUT);
        return ResponseBuilder.create().setData(result).build();
    }

    public static void main(String[] args) {
        Long time = 1482920313900l;

        Date date = new Date(time);
        String dateStr = DateUtil.dateToString(date);
        System.out.println(dateStr);
        System.out.println(new Date().getTime());
    }

}
